<template>
  <div>
    <!-- 按钮 -->
    <el-button type="primary" @click="TianJia" style="margin-bottom: 10px"
      >添加</el-button
    >
    <!-- 表格組件 -->
    <!-- 将来要展示数据--数组类型 -->
    <el-table style="width: 100%" :data="list" border>
      <!-- column每一列 -->
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="tmName" label="品牌名称" width="width" />
      <el-table-column prop="prop" label="品牌LOGO" width="width">
        <!-- 作用域插槽 -->
        <template slot-scope="{ row }">
          <img :src="row.logoUrl" alt="" style="width: 160px; height: 80px" />
        </template>
      </el-table-column>
      <el-table-column prop="prop" label="仓库" width="width">
        <template slot-scope="{ row }">
          <!-- 将品牌信息传递给update函数 -->
          <el-button
            type="warning"
            size="mini"
            icon="el-icon-edit"
            @click="update(row)"
            >修改</el-button
          >
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="open(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分頁器 -->
    <el-pagination
      style="textalign: center"
      :page-sizes="[3, 5, 7]"
      :total="total"
      layout="prev, pager, next, jumper,->,total, sizes"
      :page-size="limit"
      :current-page="page"
      :pager-count="5"
      @size-change="handleSizeChange"
      @current-change="getPageList"
    />
    <!-- 对话框 -->
    <el-dialog title="添加品牌" :visible.sync="dialogFormVisible">
      <!-- 绑定收集信息 -->
      <el-form :model="tmForm" :rules="rules" ref="fromrules">
        <!-- prop添加验证的字段 -->
        <el-form-item label="品牌名称" :label-width="'100px'" prop="tmName">
          <el-input
            autocomplete="off"
            style="width: 300px"
            v-model="tmForm.tmName"
          ></el-input>
        </el-form-item>
        <el-form-item label="上传图片" :label-width="'100px'" prop="logoUrl">
          <!-- 这里收集数据不能使用v-model，因为不是表单元素
              action：设置图片上传的地址(地址前加dev-api是因为设置了代理)
              on-success:上传成功执行一次
              before-upload：上传之前执行一次
           -->
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addORupdate">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "TradeMark",
  data() {
    return {
      page: 1,
      limit: 3,
      total: 0,
      // 品牌属性
      list: [],
      // 对话框显示与隐藏
      dialogFormVisible: false,
      // 收集品牌信息
      tmForm: {
        tmName: "",
        logoUrl: "",
      },
      // 表单验证规则
      rules: {
        // 品牌名称验证规则
        tmName: [
          { required: true, message: "请输入品牌名称", trigger: "blur" }, //required：是否必填 message：提示信息  trigger：触发条件，用户行为
          {
            require: true,
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "change",
          }, //长度验证
        ],
        // 品牌logo验证规则
        logoUrl: [{ required: true, message: "请上传图片" }],
      },
    };
  },
  mounted() {
    this.getPageList();
  },
  methods: {
    // 获取数据
    async getPageList(pager = 1) {
      this.page = pager;
      const { page, limit } = this;
      const res = await this.$API.trademark.reqTradeMarkList(page, limit);
      if (res.code === 200) {
        this.list = res.data.records;
        this.total = res.data.total;
      } else {
        alert(res.message);
      }
    },
    handleSizeChange(limit) {
      this.limit = limit;
      // 判断一下当前页有无数据，无数据展示上一页
      this.getPageList(this.list.length > 0 ? this.page : this.page - 1);
    },
    // 添加按钮
    TianJia() {
      this.dialogFormVisible = true;
      // 清空数据
      this.tmForm = { tmName: "", logoUrl: "" };
    },
    // 修改按钮
    update(row) {
      this.dialogFormVisible = true;
      // this.tmForm = row 这里不能让直接将row的值赋值给tmForm,因为表单展示的是row的数据如果让tmForm指向row那将会导致修改tmForm的同时也修改了row
      // 用浅拷贝
      this.tmForm = { ...row };
    },
    // 图片上传成功
    handleAvatarSuccess(res, file) {
      // 收集图片数据
      this.tmForm.logoUrl = res.data;
    },
    // 图片上传之前
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 确认添加
    addORupdate() {
      this.dialogFormVisible = false;
      // 验证表单数据是否符合
      this.$refs["fromrules"].validate(async (success) => {
        if (success) {
          // 发请求添加或修改
          const res = await this.$API.trademark.reqBaseTrademark(this.tmForm);
          if (res.code === 200) {
            // 弹出提示信息
            this.$message({
              message: this.tmForm.id ? "修改成功" : "添加成功",
              type: "success",
            });
            // 重新获取列表
            this.getPageList(this.tmForm.id ? this.page : 1);
          }
        } else {
          return false;
        }
      });
    },
    // 弹窗
    open(row) {
      this.$confirm("确定要删除该品牌信息吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 调用删除品牌方法
          const res = await this.$API.trademark.reqDeleteTrademark(row.id);
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getPageList(this.list.length > 1 ? this.page : this.page - 1);
          } else {
            this.$message({
              type: "danger",
              message: "删除失败!",
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
